<template>
    <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        @close="clear"
        :close-on-click-modal='false'
        class="companies-dialog"
        width="800px">
        <section class="dialog-body">
            <el-tabs value="base" class="tab">
                <el-tab-pane label="客户基本信息" name="base">
                    <el-form
                        ref="form"
                        :model="form"
                        :rules="rules"
                        :validate-on-rule-change="false"
                        label-width="170px"
                        size="mini"
                        class="form-section">
                        <el-form-item label="公司名称" prop="companyName">
                            <el-input
                                v-model="form.companyName"
                                :disabled="companyNameDisable"
                                placeholder="请输入">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="所属行业" prop="industry">
                            <!-- <el-select v-model="form.industry" placeholder="请选择">
                                <el-option
                                    v-for="item in industryList"
                                    :key="item"
                                    :label="item"
                                    :value="item">
                                </el-option>
                            </el-select> -->
                                <el-autocomplete
                                    popper-class="search-industry-autocomplete"
                                    v-model="form.industry"
                                    :fetch-suggestions="searchIndustry"
                                    placeholder="请输入"
                                    :trigger-on-focus="false"
                                    @select="selectIndustry"
                                ></el-autocomplete>
                        </el-form-item>
                        <el-form-item label="联络人" prop="accountingManager">
                            <el-input v-model="form.accountingManager" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="联络人手机号" prop="mobile">
                            <el-input v-model="form.mobile" placeholder="请输入"></el-input>
                        </el-form-item>
                       <!-- <el-form-item label="联络人微信号" prop="weChartAccount">
                            <el-input v-model="form.weChartAccount" placeholder="请输入"></el-input>
                        </el-form-item> -->
                        <el-form-item label="社会统一信用代码" prop="businessLicenseNumber">
                            <el-input v-model="form.businessLicenseNumber" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="纳税类型" prop="payTaxesType">
                            <el-select v-model="form.payTaxesType" placeholder="请选择">
                                <el-option
                                    v-for="(item, index) in payTaxesTypeList"
                                    :key="item"
                                    :label="item"
                                    :value="index">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="电子税务局密码" prop="password">
                            <el-input v-model="form.password" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item v-if="form.payTaxesType === 1" label="核算精度" prop="accuracyType">
                            <el-radio-group v-model="form.accuracyType">
                                <el-radio :label="1">税务精度</el-radio>
                                <el-radio :label="0">财务精度</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="个税申报密码" prop="incomeTaxPassword">
                            <el-input v-model="form.incomeTaxPassword" placeholder="请输入"></el-input>
                        </el-form-item>

                        <el-form-item label="报税员电话/账号" prop="taxAgentMobileAccount">
                            <el-input v-model="form.taxAgentMobileAccount" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="城建税税率" prop="urbanTaxRate">
                            <el-select v-model="form.urbanTaxRate" placeholder="请选择">
                                <el-option
                                    v-for="item in urbanTaxRateList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="地区" prop="region">
                            <el-select v-model="form.region" placeholder="请选择">
                                <el-option
                                    v-for="item in regionList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                        </el-form-item>
                        <el-form-item label="是否签署缴税三方协议" prop="agreement">
                            <el-radio-group v-model="form.agreement">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="2">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="是否有个人经营所得税" prop="incomeBuzType">
                            <el-radio-group v-model="form.incomeBuzType" @change="onPeopleMangeTax">
                                <el-radio :label="1">有</el-radio>
                                <el-radio :label="2">无</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="个人经营所得税类型" prop="buzDateType" v-if="form.incomeBuzType === 1">
                            <el-radio-group v-model="form.buzDateType">
                                <el-radio :label="0">月报</el-radio>
                                <el-radio :label="1">季报</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="个人经营所得税-人员信息表" v-if="form.incomeBuzType === 1" prop="incomeBuzFormData">
                            <el-upload
                            :multiple="false"
                            :limit="1"
                            :with-credentials="true"
                            :on-remove="removeBalanceStatementFile"
                            :on-exceed="onExceed"
                            :data="{ key: 'file' }"
                            accept=".xlsx,.xls"
                            action="/api/companies/uploadIncomeBuzFile"
                            :http-request="uploadFile"
                            class="upload-item"
                            >
                            <el-button size="small" type="primary"
                                >上传表格 excel</el-button
                            >
                            </el-upload>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            <financeAndEtaxInfo v-if="type === 'add'" ref="financeAndEtaxInfo" :cName.sync='cName'/>
            <el-tabs value="suppliers-and-customers" class="suppliers-and-customers">
                <el-tab-pane label="供应商库 与 客户库" name="suppliers-and-customers">
                    <section class="explain">
                        <div>
                            1. 请务必保证表格内公司名称与发票上名称相同，否则将影响会计凭证生成
                        </div>
                        <div>
                            2. 可从Excel复制内容粘贴至表格
                        </div>
                        <div>
                            3. 该名单将根据每月发票信息自动更新
                        </div>
                    </section>
                    <section class="table-container">
                        <section class="suppliers">
                            <el-table
                                border
                                :data="suppliersTableData"
                                tooltip-effect="dark"
                                style="width: 100%">
                                <el-table-column
                                    label="编号"
                                    width="60"
                                    type="index"
                                    align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="companyName"
                                    label="公司名称">
                                    <template slot-scope="scope">
                                        <template v-if="scope.row.type === 'show'">
                                            {{scope.row.companyName}}
                                        </template>
                                        <el-input
                                            v-else
                                            v-model="scope.row.companyName"
                                            :maxlength="20"
                                            placeholder="请输入公司名称"
                                            size="mini">
                                        </el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-circle-plus-outline"
                                class="add-btn"
                                @click="addSupplierOrcustomer('supplier')">
                                添加
                            </el-button>
                        </section>
                        <section class="customers">
                            <el-table
                                border
                                :data="customersTableData"
                                tooltip-effect="dark"
                                style="width: 100%">
                                <el-table-column
                                    label="编号"
                                    width="60"
                                    type="index"
                                    align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="companyName"
                                    label="公司名称">
                                    <template slot-scope="scope">
                                        <template v-if="scope.row.type === 'show'">
                                            {{scope.row.companyName}}
                                        </template>
                                        <el-input
                                            v-else
                                            v-model="scope.row.companyName"
                                            :maxlength="20"
                                            placeholder="请输入公司名称"
                                            size="mini">
                                        </el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-button
                                @click="addSupplierOrcustomer('customer')"
                                type="primary"
                                size="mini"
                                icon="el-icon-circle-plus-outline"
                                class="add-btn">
                                添加
                            </el-button>
                        </section>
                    </section>
                </el-tab-pane>
            </el-tabs>
        </section>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
            <el-button type="primary" @click="submit" size="mini" :loading="saveBtnLoading">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import map, { urbanTaxRateList, regionList } from '@/components/map.js';
import utiles from '@/components/utiles.js';
import 'element-ui/lib/theme-chalk/upload.css';
import financeAndEtaxInfo from './finance-and-etax-info';
// 财税信息 finance-and-etax-info

export default {
    components: {
        financeAndEtaxInfo
    },
    data() {
        const requiredRule = {
            required: true,
            trigger: 'blur',
            message: '请填写'
        };
        const requiredSelectRule = {
            required: true,
            trigger: 'blur',
            message: '请选择'
        };
        return {
            dialogVisible: false,
            title: '',
            type: '',
            companyData: null,
            industryList: map.industryList,
            payTaxesTypeList: map.payTaxesTypeList,
            // 文件列表
            balanceStatementFileList: [],
            incomeStatementFileList: [],
            bankStatementFileList: [],
            companyNameDisable: false,
            form: {
                companyName: '',
                industry: '',
                accountingManager: '',
                mobile: '',
                weChartAccount: '',
                businessLicenseNumber: '',
                payTaxesType: '',
                accuracyType: '',
                password: '',
                incomeTaxPassword: '',
                taxAgentMobileAccount: '',
                urbanTaxRate: '',
                region: '',
                agreement: '',
                incomeBuzType: 2,
                buzDateType: 0,
                incomeBuzFormData: null
            },
            rules: {
                companyName: requiredRule,
                industry: requiredSelectRule,
                accountingManager: requiredRule,
                mobile: requiredRule,
                weChartAccount: requiredRule,
                businessLicenseNumber: requiredRule,
                payTaxesType: requiredRule,
                accuracyType: requiredSelectRule,
                password: requiredRule,
                incomeTaxPassword: requiredRule,
                taxAgentMobileAccount: requiredRule,
                urbanTaxRate: requiredRule,
                region: requiredRule,
                agreement: requiredSelectRule,
                incomeBuzType: requiredSelectRule,
                buzDateType: requiredSelectRule,
                incomeBuzFormData: requiredSelectRule,
            },
            suppliersTableData: [],
            customersTableData: [],
            urbanTaxRateList,
            regionList,
            saveBtnLoading: false,
            cName: '',
        };
    },
    methods: {

        /**
         * 打开弹框
         */
        open(companyData) {
            this.dialogVisible = true;
            this.companyData = companyData || {};
            // 编辑
            if (companyData) {
                this.type = 'modify';
                if (companyData.incomeBuzType === 1) {
                  companyData.incomeBuzFormData = {};
                }
                this.companyNameDisable = true;
                this.title = companyData.companyName;
                // 回填数据
                for (let key of Object.keys(this.form)) {

                    if (key === 'urbanTaxRate' && !companyData[key]) {
                       companyData[key] = null
                    }
                    this.form[key] = companyData[key];
                }
                // 供应商库 与 客户库
                companyData.suppliers.forEach(item => {
                    this.suppliersTableData.push({
                        companyName: item,
                        type: 'show'
                    });
                });
                
                companyData.customers.forEach(item => {
                    this.customersTableData.push({
                        companyName: item,
                        type: 'show'
                    });
                });

                console.log(5555, companyData)
            }
            // 新建
            else {
                this.type = 'add';
                this.title = '新建客户';
                this.companyNameDisable = false;
            }
        },

        /**
         * 添加供应商或客户
         */
        addSupplierOrcustomer(type) {
            this[`${type}sTableData`].push({
                companyName: '',
                type: 'new'
            });
        },

        /**
         * 清除表单和验证
         */
        clear() {
            // 清除数据
            this.suppliersTableData = [];
            this.customersTableData = [];
            for (let key of Object.keys(this.form)) {
                this.form[key] = key === 'buzDateType' ? 0 : '';
            }
            // 清除校验
            this.$refs.form.clearValidate();
        },

        /**
         * 点击确定后的提交操作
         */
        submit() {
            this.$refs.form.validate(result => {
                // 校验成功
                if (result) {
                    this.postData();
                }
            });
        },

        /**
         * 提交数据
         */
        postData() {
            // 添加公司
            const suppliers = [];
            const customers = [];

            // 税收优惠政策
            let financeAndEtaxInfo = {};
            if (this.$refs.financeAndEtaxInfo) {
                financeAndEtaxInfo = this.$refs.financeAndEtaxInfo.getValue();
            }
            this.suppliersTableData.forEach(item => {
                suppliers.push(item.companyName);
            });

            this.customersTableData.forEach(item => {
                customers.push(item.companyName);
            });
            const currentUser = utiles.getCurrentUser();
            this.saveBtnLoading = true;
            Promise.all([
                this.$http.post(`/companies/${this.type}`, {
                    bCompanyName: currentUser.bCompanyName,
                    ...this.form,
                    ...financeAndEtaxInfo.form,
                    suppliers,
                    customers
                }),
                this.$refs.financeAndEtaxInfo ? this.$http.post(`/taxesStandard/initialAddTaxesStandard`, {
                    bName: currentUser.bCompanyName,
                    cName: this.form.companyName,
                    ...financeAndEtaxInfo.taxesStandardInfo
                }) : Promise.resolve(),
            ]).then(async ([res, _addTaxesStandardRes]) => {
                // 成功
                const suppliers = [];
                const customers = [];
                this.suppliersTableData.forEach(item => {
                    suppliers.push(item.companyName);
                });

                this.customersTableData.forEach(item => {
                    customers.push(item.companyName);
                });

                if (res.data.isSuccess) {
                    let serialNumber;
                    if (this.type === 'add') {
                        if (this.form.incomeBuzType === 1) {
                          await this.uploadIncomeBuzFile(res.data.customerId);
                        }
                        serialNumber = res.data.serialNumber;
                        this.$message.success('新建客户成功');
                    } else {
                         this.$message.success('编辑客户成功');
                    }

                    this.$emit(this.type, {
                        serialNumber,
                        ...this.form,
                        suppliers,
                        customers
                    });
                    this.dialogVisible = false;
                }
                else {
                    this.$message.error(res.data.message);
                }
            }).finally(() => {
                this.saveBtnLoading = false;
            });
        },
        /**
     * 超出最大上传数
     */
    onExceed() {
      this.$message.error("当前文件已上传，如需更新请删除后再重新上传");
    },
    onPeopleMangeTax(data) {
        if (data === 2) {
            this.form['buzDateType'] = 0;
        }
    },

    /**
     * 上传文件
     *
     * @param {Object} fileData 文件数据
     */
    uploadFile(fileData) {
      const formData = new FormData();
      // 键值
      formData.append("file", fileData.file);
      this.form.incomeBuzFormData = formData;
      if (this.type === 'modify') {
         this.uploadIncomeBuzFile(this.companyData.id).catch(err => {
             this.form.incomeBuzFormData = null;
         });
      }
    },
      /**
     * 移除
     */
    removeBalanceStatementFile() {
      this.incomeBuzFormData = "";
    },
    uploadIncomeBuzFile(customerId) {
        console.log(this.form.incomeBuzFormData)
          this.$http
        .post('/companies/uploadIncomeBuzFile', this.form.incomeBuzFormData, {
          params: {
              customerId,
              incomeBuzType: this.form.incomeBuzType
          },
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .catch((err) => {
          this.$message('个人经营所得税-人员信息表上传失败，请重新上传');
          console.error(err);
          throw err;
        });
    },
    searchIndustry(queryString, cb){
        let results;
        console.log("调用后端seachIndustry");
        this.$http.get("/common/searchIndustry", {params:{keyword: queryString}}).then( res => {
            if(res.code == 0){
                results = res.data.industryList.map((itemValue, index) => {
                    return {
                        id: index,
                        value: itemValue
                    }
                });
                cb(results);
            }
        })
        // var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
    },
    selectIndustry(item){
        console.log("选择：", item);
    }
  },

  watch:{
      form:{
          deep:true,
          handler: function(newVal, oldVal){
            this.cName = newVal.companyName;
          }
      }
  }
}
</script>

<style lang="less" scoped>
@import '../../assets/var.less';
.dialog-body {
    max-height: 500px;
    padding: 0 30px;
    overflow: auto;
}
.form-section {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
        flex: 1;
        min-width: 47%;
        max-width: 47%;
        .el-select,
        .el-upload {
            display: block;
        }
    }
}
.suppliers-and-customers {

    .explain {
        padding-bottom: 5px;
        color: @color-grey-low;
        font-size: 12px;
        line-height: 1.2em;
    }

    .table-container {
        display: flex;
        .suppliers,
        .customers {
            flex: 0 0 360px;
            margin-right: 5px;
        }
        .add-btn {
            float: right;
            margin-top: 5px;
        }
    }
}

</style>
<style lang="less">
.companies-dialog .el-dialog__body {
    padding: 0;
}

.search-industry-autocomplete {
    background: white;
    border-radius: 3px;
    border: 1px solid rgb(248, 245, 245);
    margin-top: 0 !important;
    div{
        max-height: 200px;        
        ul {
            margin: 0;
            padding: 0;
        }
        li {
            border: 1px solid rgb(247, 244, 244);
            list-style-type: none;
            margin:0px;
            padding-left: 0;
            &:hover, &.highlighted {
                background: rgba(235, 232, 232, 0.9);
                cursor:pointer;
            }
        }
    }
}
</style>
